//$URL: http://dasding.googlecode.com/svn/branches/testzeugs/data/dao/couchDB/src/main/java/de/piratech/dasding/data/database/couch/UserDataImpl.java $
//$Id: UserDataImpl.java 89 2012-11-12 14:55:42Z amuthmann@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.data.database.couch;

import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.data.database.UserData;
import java.util.List;
import org.ektorp.CouchDbConnector;
import org.ektorp.support.CouchDbRepositorySupport;
import org.ektorp.support.GenerateView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
public class UserDataImpl extends CouchDbRepositorySupport<User>
        implements UserData {

  private static final Logger LOG = LoggerFactory.getLogger(UserData.class);

  public UserDataImpl(CouchDbConnector pCouchDbConnector) {
    super(User.class, pCouchDbConnector, "User");
    initStandardDesignDocument();
  }

  @Override
  public User createUser(User pUser) throws DatabaseException {
    LOG.debug("createUser({})", pUser);
    // ensure the user's login is unique 
    if (getUser(pUser.getName()) != null) {
      throw new DatabaseException("Username is not unique");
    }
    db.create(pUser);
    return pUser;
  }

  @Override
  public void deleteUser(User pUser) {
    LOG.debug("deleteUser({})", pUser);
    remove(pUser);
  }

  @Override
  public void updateUser(User pUser) {
    LOG.debug("updateUser({})", pUser);
    update(pUser);
  }

  @Override
  public User getUser(String pName) {
    LOG.debug("getUser({})", pName);
    return findByName(pName);

  }

  /**
   * Used to autogenerate a view which allows lookup by username instead of id
   *
   * @param pName
   * @return
   */
  @GenerateView
  private User findByName(String pName) {
    List<User> users = queryView("by_name", pName);
    return users.isEmpty() ? null : users.get(0);
  }
}
